package rlyy.framework.core.resolver.argument;

import com.google.common.base.Strings;
import rlyy.framework.core.common.request.FullRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.Parameter;
import java.util.Optional;

/**
 *
 * 处理参数注解是RequestParam() 参数类型是简单数据类型解析器
 * @author yuanqinglong
 * @since 2020/9/14 15:07
 */
@Component
public class RequestParamMethodArgumentResolver implements MyHandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(Parameter parameter) {
        return parameter.isAnnotationPresent(RequestParam.class) && BeanUtils.isSimpleProperty(parameter.getType());
    }

    @Override
    public Object resolveArgument(Parameter parameter, FullRequest fullRequest) {
        RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
        String key = Optional.ofNullable(Strings.emptyToNull(requestParam.name()))
                .orElseGet(requestParam::value);
        return Optional.ofNullable(fullRequest.getData())
                .map(d-> d.getObject(key, parameter.getType())).orElse(null);
    }

    @Override
    public int getOrder() {
        return 30;
    }
}
